import path from "node:path";
import { ChatCompletion } from "@baiducloud/qianfan";
import "dotenv/config";
import OpenAI from "openai";
import fsp from "fs/promises";
import fs from "fs";

// 百度千帆模型
const demoBaidu = async () => {
  const client = new ChatCompletion();
  const stream = await client.chat(
    {
      messages: [
        {
          role: "user",
          content: "你好"
        },
        {
          role: "assistant",
          content: "如果您有任何问题，请随时向我提问。"
        },
        {
          role: "user",
          content: "我在北京，周末可以去哪里玩?"
        }
      ],
      stream: true
    },
    "ERNIE-Speed-128K"
  );
  for await (const chunk of stream as AsyncIterableIterator<any>) {
    console.log(chunk);
  }
};

//阿里云百炼
const demoAli = async () => {
  const client = new OpenAI({
    apiKey: process.env["DASHSCOPE_API_KEY"],
    baseURL: "https://dashscope.aliyuncs.com/compatible-mode/v1"
  });

  // 识别文档内容
  /* const fileObj = await client.files.create({
    file: fs.createReadStream(path.join(process.cwd(), "src/assets/mss.pdf")),
    purpose: "file-extract" as any
  });
  const resp = await client.chat.completions.create({
    messages: [
      { role: "system", content: "You are a helpful assistant." },
      { role: "system", content: `fileid://${fileObj.id}` },
      { role: "user", content: "请帮忙概括文件是什么内容" }
    ],
    model: "qwen-long"
  });
  console.log("resp--", resp.choices[0].message); */

  // 图片识别
  const imageBuffer = await fsp.readFile(
    path.join(process.cwd(), "src/assets/mm.jpg")
  );
  const base64Image = imageBuffer.toString("base64");
  const resp = await client.chat.completions.create({
    messages: [
      {
        role: "user",
        content: [
          { type: "text", text: "图中人物的性别" },
          {
            type: "image_url",
            image_url: { url: `data:image/jpg;base64,${base64Image}` }
            // image_url: { url: "https://dashscope.oss-cn-beijing.aliyuncs.com/images/dog_and_girl.jpeg"}
          }
        ]
      }
    ],
    model: "qwen-vl-plus"
  });
  console.log("resp--", resp.choices[0].message.content);

  // 基本功能
  /* const stream = await client.chat.completions.create({
    messages: [
      { role: "system", content: "你现在是个6岁孩子，请模仿儿童的口吻回答" },
      { role: "user", content: "西游记讲了什么内容" }
    ],
    model: "qwen-turbo",
    stream: true
  });
  for await (const chunk of stream) {
    console.log(chunk.choices[0].delta);
  } */
};
